package com.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by baiguantao on 2018/1/4.
 */
public class JdkProxy {

    /**
     * jdk动态代理   是基于接口方式的代理
     */
    @org.junit.Test
    public void JdkProxy() {
        MenuService m = (MenuService) Proxy.newProxyInstance(JdkProxy.class.getClassLoader(),
                new Class[]{MenuService.class}, new InvocationHandler() {
                    MenuService target = new MenuServiceImpl();

                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("执行前");
                        method.invoke(target, args);
                        System.out.println("执行后");
                        return target;
                    }
                });

        m.Hello();
    }
}

interface MenuService {
    void Hello();
}

class MenuServiceImpl implements MenuService {
    private String name = "defaultName";

    public String getName() {
        return name;
    }

    public void Hello() {
        System.out.println("Hello:" + getName());
    }

    public void setName(String name) {
        this.name = name;
    }


}
